﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace PSSymbolStore.Manager.Windows
{
    public partial class SearchResults : UserControl
    {
        public SearchResults()
        {
            InitializeComponent();
        }

        private List<AddTransaction> _transactions;

        public List<AddTransaction> Transactions
        {
            get
            {
                return _transactions;
            }
            set
            {
                _transactions = value;
                UpdateListView();
            }
        }

        public event EventHandler<SearchResultsEventArgs> TransactionSelected;

        protected virtual void OnTransactionSelected(SearchResultsEventArgs e)
        {
            try
            {
                EventHandler<SearchResultsEventArgs> evt = TransactionSelected;
                if (evt != null)
                {
                    evt(this, e);
                }
            }
            catch { }
        }

        private void UpdateListView()
        {
            if (InvokeRequired)
            {
                BeginInvoke((MethodInvoker)UpdateListView);
                return;
            }

            //listView.Items.Clear();
            flowLayoutPanel.Controls.Clear();

            if ((_transactions != null) && (_transactions.Count > 0))
            {
                foreach (AddTransaction tran in _transactions)
                {
                    flowLayoutPanel.Controls.Add(new TransactionPreview { Transaction = tran });
                    //listView.Items.Add(TransactionToListViewItem(tran));
                }
            }
            else
            {
                OnTransactionSelected(SearchResultsEventArgs.Empty);
            }
        }

        private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // When we double click on an item, we've selected it
            SelectCurrentTransaction();
        }

        private void listView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SelectCurrentTransaction();
            }
        }

        private void SelectCurrentTransaction()
        {
            if (listView.SelectedItems.Count > 0)
            {
                OnTransactionSelected(new SearchResultsEventArgs(listView.SelectedItems[0].Tag as AddTransaction));
            }
        }
    }
}
